<template>
  <div class="debug-master">
    <div class="game-header">
      <el-button :icon="ArrowLeft" @click="goBack">返回</el-button>
      <div class="game-title">
        <h1>🐛 代码调试大师</h1>
        <p>找出代码中的Bug，训练调试技能和代码审查能力</p>
      </div>
      <div class="game-stats">
        <el-statistic title="发现Bug" :value="gameStats.bugsFound" />
        <el-statistic title="正确率" :value="gameStats.accuracy" suffix="%" />
        <el-statistic title="获得积分" :value="gameStats.points" />
      </div>
    </div>

    <!-- 关卡列表 -->
    <div class="levels-container">
      <div 
        v-for="level in levels" 
        :key="level.id"
        class="level-card"
        :class="{ 
          completed: level.completed,
          locked: level.locked,
          current: level.id === currentLevel?.id 
        }"
        @click="!level.locked && selectLevel(level)"
      >
        <div class="level-number">关卡 {{ level.id }}</div>
        <h3>{{ level.title }}</h3>
        <p>{{ level.description }}</p>
        <div class="level-info">
          <el-tag :type="getLevelType(level.difficulty)" size="small">
            {{ level.difficulty }}
          </el-tag>
          <span class="bug-count">
            <el-icon><Warning /></el-icon>
            {{ level.bugCount }} 个Bug
          </span>
          <span class="points">
            <el-icon><Trophy /></el-icon>
            {{ level.points }}
          </span>
        </div>
        <el-icon v-if="level.completed" class="completed-icon"><CircleCheck /></el-icon>
        <el-icon v-if="level.locked" class="lock-icon"><Lock /></el-icon>
      </div>
    </div>

    <!-- 调试界面 -->
    <el-dialog
      v-model="showDebugDialog"
      :title="`关卡 ${currentLevel?.id}: ${currentLevel?.title}`"
      width="90%"
      top="5vh"
      fullscreen
      :close-on-click-modal="false"
    >
      <div class="debug-interface">
        <div class="debug-sidebar">
          <div class="mission-info">
            <h3>🎯 任务目标</h3>
            <p>{{ currentLevel?.objective }}</p>
            <el-alert 
              :title="`找出 ${currentLevel?.bugCount} 个Bug`" 
              type="warning" 
              :closable="false"
              show-icon
            />
          </div>

          <div class="bugs-found">
            <h3>🐛 已发现的Bug</h3>
            <div class="bug-list">
              <div 
                v-for="(bug, index) in foundBugs" 
                :key="index"
                class="bug-item"
                :class="{ correct: bug.isCorrect, incorrect: !bug.isCorrect }"
              >
                <div class="bug-line">第 {{ bug.line }} 行</div>
                <div class="bug-type">{{ bug.type }}</div>
                <el-icon v-if="bug.isCorrect"><Check /></el-icon>
                <el-icon v-else><Close /></el-icon>
              </div>
              <div v-if="foundBugs.length === 0" class="empty-bugs">
                还没有发现Bug，点击代码行标记Bug位置
              </div>
            </div>
          </div>

          <div class="hints-section">
            <h3>💡 提示</h3>
            <el-button 
              v-if="availableHints > 0"
              type="warning"
              size="small"
              @click="showHint"
            >
              使用提示 (剩余 {{ availableHints }})
            </el-button>
            <div v-if="currentHint" class="hint-text">
              {{ currentHint }}
            </div>
          </div>

          <div class="actions">
            <el-button 
              type="primary" 
              size="large"
              :disabled="foundBugs.length === 0"
              @click="checkAnswer"
            >
              提交答案
            </el-button>
            <el-button size="large" @click="resetLevel">重置</el-button>
          </div>
        </div>

        <div class="code-panel">
          <div class="code-header">
            <h3>{{ currentLevel?.filename }}</h3>
            <div class="code-info">
              <span>{{ currentLevel?.language }}</span>
              <span>{{ currentLevel?.codeLines?.length || 0 }} 行代码</span>
            </div>
          </div>
          <div class="code-editor-wrapper">
            <div class="line-numbers">
              <div 
                v-for="(_, index) in currentLevel?.codeLines" 
                :key="index"
                class="line-number"
                :class="{ 
                  marked: isLineMarked(index + 1),
                  correct: isLineCorrect(index + 1),
                  wrong: isLineWrong(index + 1)
                }"
                @click="markBugLine(index + 1)"
              >
                {{ index + 1 }}
              </div>
            </div>
            <div class="code-content">
              <pre 
                v-for="(line, index) in currentLevel?.codeLines" 
                :key="index"
                class="code-line"
                :class="{ 
                  marked: isLineMarked(index + 1),
                  correct: isLineCorrect(index + 1),
                  wrong: isLineWrong(index + 1)
                }"
                @click="markBugLine(index + 1)"
              ><code>{{ line }}</code></pre>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- Bug类型选择对话框 -->
    <el-dialog
      v-model="showBugTypeDialog"
      title="选择Bug类型"
      width="400px"
    >
      <div class="bug-types">
        <el-button 
          v-for="type in bugTypes" 
          :key="type"
          @click="selectBugType(type)"
          class="bug-type-btn"
        >
          {{ type }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft, Trophy, Warning, CircleCheck, Lock,
  Check, Close
} from '@element-plus/icons-vue'

const router = useRouter()

// 游戏统计
const gameStats = ref({
  bugsFound: 15,
  accuracy: 87,
  points: 650
})

// 关卡数据
const levels = ref([
  {
    id: 1,
    title: '变量未定义',
    description: '找出未定义的变量',
    difficulty: '简单',
    bugCount: 2,
    points: 50,
    completed: true,
    locked: false,
    language: 'JavaScript',
    filename: 'app.js',
    objective: '找出代码中未定义的变量，这些变量在使用前没有声明',
    codeLines: [
      'function calculateTotal(items) {',
      '  let total = 0;',
      '  for (let i = 0; i < items.length; i++) {',
      '    total += items[i].price * quantity;', // Bug: quantity未定义
      '  }',
      '  console.log(result);', // Bug: result未定义
      '  return total;',
      '}'
    ],
    bugs: [
      { line: 4, type: '变量未定义' },
      { line: 6, type: '变量未定义' }
    ],
    hints: [
      '检查第4行使用的变量是否都已定义',
      '第6行console.log中的变量名称是否正确'
    ]
  },
  {
    id: 2,
    title: '语法错误',
    description: '找出代码中的语法错误',
    difficulty: '简单',
    bugCount: 3,
    points: 60,
    completed: false,
    locked: false,
    language: 'JavaScript',
    filename: 'utils.js',
    objective: '找出代码中的语法错误，包括括号、引号、分号等',
    codeLines: [
      'function greet(name {', // Bug: 缺少右括号
      '  if (name === "admin") {',
      '    return "Welcome, admin!',  // Bug: 缺少右引号
      '  } else {',
      '    return "Hello, " + name;',
      '  }', // Bug: 缺少函数结束括号
      ''
    ],
    bugs: [
      { line: 1, type: '括号不匹配' },
      { line: 3, type: '引号不匹配' },
      { line: 6, type: '缺少闭合括号' }
    ],
    hints: [
      '检查第1行的函数参数括号',
      '注意字符串的引号是否完整',
      '函数是否正确闭合'
    ]
  },
  {
    id: 3,
    title: '逻辑错误',
    description: '找出代码逻辑问题',
    difficulty: '中等',
    bugCount: 2,
    points: 80,
    completed: false,
    locked: false,
    language: 'JavaScript',
    filename: 'calculator.js',
    objective: '找出代码中的逻辑错误，这些错误不会导致程序崩溃，但会产生错误的结果',
    codeLines: [
      'function findMax(arr) {',
      '  let max = 0;', // Bug: 如果数组全是负数，初始值应该是arr[0]
      '  for (let i = 0; i < arr.length; i++) {',
      '    if (arr[i] < max) {', // Bug: 应该是 >
      '      max = arr[i];',
      '    }',
      '  }',
      '  return max;',
      '}'
    ],
    bugs: [
      { line: 2, type: '初始化错误' },
      { line: 4, type: '比较运算符错误' }
    ],
    hints: [
      '思考max的初始值在什么情况下会有问题',
      '检查比较运算符的方向是否正确'
    ]
  },
  {
    id: 4,
    title: '数组越界',
    description: '找出数组访问越界的问题',
    difficulty: '中等',
    bugCount: 2,
    points: 90,
    completed: false,
    locked: false,
    language: 'JavaScript',
    filename: 'array-ops.js',
    objective: '找出数组访问越界和索引相关的错误',
    codeLines: [
      'function getLastThree(arr) {',
      '  return [',
      '    arr[arr.length],', // Bug: 应该是length-1
      '    arr[arr.length - 1],',
      '    arr[arr.length - 2]', // Bug: 没有检查数组长度
      '  ];',
      '}'
    ],
    bugs: [
      { line: 3, type: '数组索引错误' },
      { line: 5, type: '缺少边界检查' }
    ],
    hints: [
      '数组的最后一个元素索引是多少？',
      '如果数组长度小于3会怎样？'
    ]
  },
  {
    id: 5,
    title: '异步错误',
    description: '找出异步代码中的问题',
    difficulty: '困难',
    bugCount: 3,
    points: 120,
    completed: false,
    locked: false,
    language: 'JavaScript',
    filename: 'async.js',
    objective: '找出异步代码中的问题，包括Promise和async/await的错误使用',
    codeLines: [
      'async function fetchData() {',
      '  const response = fetch("/api/data");', // Bug: 缺少await
      '  const data = response.json();', // Bug: 缺少await
      '  return data;',
      '}',
      '',
      'function processData() {',
      '  const result = fetchData();', // Bug: 缺少await
      '  console.log(result.value);',
      '}'
    ],
    bugs: [
      { line: 2, type: '缺少await' },
      { line: 3, type: '缺少await' },
      { line: 8, type: '缺少await' }
    ],
    hints: [
      'fetch返回Promise，需要等待',
      'json()方法也是异步的',
      '调用async函数时需要await'
    ]
  }
])

const currentLevel = ref(null)
const showDebugDialog = ref(false)
const showBugTypeDialog = ref(false)
const selectedLine = ref(null)
const foundBugs = ref([])
const availableHints = ref(3)
const currentHint = ref('')

const bugTypes = [
  '变量未定义',
  '括号不匹配',
  '引号不匹配',
  '缺少闭合括号',
  '初始化错误',
  '比较运算符错误',
  '数组索引错误',
  '缺少边界检查',
  '缺少await',
  '其他'
]

const getLevelType = (difficulty) => {
  const map = { '简单': 'success', '中等': 'warning', '困难': 'danger' }
  return map[difficulty]
}

const goBack = () => {
  router.push('/learning/games/center')
}

const selectLevel = (level) => {
  currentLevel.value = level
  showDebugDialog.value = true
  foundBugs.value = []
  availableHints.value = 3
  currentHint.value = ''
}

const markBugLine = (line) => {
  selectedLine.value = line
  
  // 检查是否已标记
  const existing = foundBugs.value.find(b => b.line === line)
  if (existing) {
    ElMessage.warning('该行已标记，请标记其他行')
    return
  }
  
  // 检查是否已找到所有Bug
  if (foundBugs.value.length >= currentLevel.value.bugCount) {
    ElMessage.warning(`已标记${currentLevel.value.bugCount}个Bug，请提交答案`)
    return
  }
  
  showBugTypeDialog.value = true
}

const selectBugType = (type) => {
  const actualBug = currentLevel.value.bugs.find(b => b.line === selectedLine.value)
  const isCorrect = actualBug && actualBug.type === type
  
  foundBugs.value.push({
    line: selectedLine.value,
    type: type,
    isCorrect: isCorrect
  })
  
  showBugTypeDialog.value = false
  
  if (isCorrect) {
    ElMessage.success(`正确！发现了一个 ${type}`)
  } else {
    ElMessage.error('这里不是Bug或类型不正确')
  }
}

const isLineMarked = (line) => {
  return foundBugs.value.some(b => b.line === line)
}

const isLineCorrect = (line) => {
  const bug = foundBugs.value.find(b => b.line === line)
  return bug?.isCorrect
}

const isLineWrong = (line) => {
  const bug = foundBugs.value.find(b => b.line === line)
  return bug && !bug.isCorrect
}

const showHint = () => {
  if (availableHints.value > 0) {
    const hintIndex = 3 - availableHints.value
    currentHint.value = currentLevel.value.hints[hintIndex] || '没有更多提示了'
    availableHints.value--
  }
}

const checkAnswer = () => {
  const correctBugs = foundBugs.value.filter(b => b.isCorrect).length
  const totalBugs = currentLevel.value.bugCount
  
  if (correctBugs === totalBugs && foundBugs.value.length === totalBugs) {
    // 完美通关
    ElMessageBox.alert(
      `🎉 完美！全部找对了！\n\n获得 ${currentLevel.value.points} 积分`,
      '关卡完成',
      {
        confirmButtonText: '继续挑战',
        callback: () => {
          currentLevel.value.completed = true
          gameStats.value.bugsFound += totalBugs
          gameStats.value.points += currentLevel.value.points
          showDebugDialog.value = false
        }
      }
    )
  } else if (correctBugs > 0) {
    ElMessage.warning(`找对了 ${correctBugs}/${totalBugs} 个Bug，继续加油！`)
  } else {
    ElMessage.error('没有找对Bug，请仔细检查代码')
  }
}

const resetLevel = () => {
  foundBugs.value = []
  availableHints.value = 3
  currentHint.value = ''
  ElMessage.info('已重置关卡')
}
</script>

<style scoped>
.debug-master {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.game-header {
  display: flex;
  align-items: center;
  gap: 30px;
  margin-bottom: 30px;
  padding: 24px;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  border-radius: 12px;
  color: white;
}

.game-title {
  flex: 1;
}

.game-title h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
}

.game-title p {
  margin: 0;
  opacity: 0.9;
}

.game-stats {
  display: flex;
  gap: 40px;
}

.game-stats :deep(.el-statistic__head) {
  color: rgba(255, 255, 255, 0.8);
}

.game-stats :deep(.el-statistic__content) {
  color: white;
  font-weight: bold;
}

.levels-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.level-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.level-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.level-card.completed {
  border-left: 4px solid #67c23a;
}

.level-card.locked {
  opacity: 0.5;
  cursor: not-allowed;
}

.level-card.current {
  border: 2px solid #409eff;
}

.level-number {
  display: inline-block;
  padding: 4px 12px;
  background: #409eff;
  color: white;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
  margin-bottom: 12px;
}

.level-card h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #303133;
}

.level-card p {
  margin: 0 0 16px 0;
  color: #606266;
  font-size: 14px;
}

.level-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.bug-count, .points {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  color: #909399;
}

.completed-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 28px;
  color: #67c23a;
}

.lock-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 28px;
  color: #909399;
}

/* 调试界面 */
.debug-interface {
  display: grid;
  grid-template-columns: 350px 1fr;
  gap: 20px;
  height: calc(100vh - 200px);
}

.debug-sidebar {
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow-y: auto;
}

.debug-sidebar h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #303133;
}

.mission-info {
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
}

.mission-info p {
  margin: 0 0 12px 0;
  line-height: 1.6;
}

.bugs-found {
  padding: 16px;
  background: #fff7e6;
  border-radius: 8px;
}

.bug-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.bug-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: white;
  border-radius: 6px;
  border-left: 3px solid #e6a23c;
}

.bug-item.correct {
  border-left-color: #67c23a;
}

.bug-item.incorrect {
  border-left-color: #f56c6c;
}

.bug-line {
  font-weight: bold;
  color: #303133;
}

.bug-type {
  flex: 1;
  margin-left: 12px;
  font-size: 13px;
  color: #606266;
}

.empty-bugs {
  padding: 20px;
  text-align: center;
  color: #909399;
  font-size: 13px;
}

.hints-section {
  padding: 16px;
  background: #e6f7ff;
  border-radius: 8px;
}

.hint-text {
  margin-top: 12px;
  padding: 12px;
  background: white;
  border-radius: 4px;
  color: #606266;
  line-height: 1.6;
}

.actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 代码面板 */
.code-panel {
  display: flex;
  flex-direction: column;
  background: #1e1e1e;
  border-radius: 8px;
  overflow: hidden;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #2d2d2d;
  color: white;
}

.code-header h3 {
  margin: 0;
  font-size: 14px;
}

.code-info {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #999;
}

.code-editor-wrapper {
  display: grid;
  grid-template-columns: 50px 1fr;
  flex: 1;
  overflow-y: auto;
}

.line-numbers {
  background: #2d2d2d;
  padding: 16px 0;
  text-align: center;
  user-select: none;
}

.line-number {
  padding: 2px 8px;
  color: #858585;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 13px;
  line-height: 1.6;
  cursor: pointer;
  transition: all 0.2s ease;
}

.line-number:hover {
  background: #3e3e3e;
  color: #fff;
}

.line-number.marked {
  background: #e6a23c;
  color: white;
  font-weight: bold;
}

.line-number.correct {
  background: #67c23a !important;
}

.line-number.wrong {
  background: #f56c6c !important;
}

.code-content {
  padding: 16px;
  overflow-x: auto;
}

.code-line {
  margin: 0;
  padding: 2px 12px;
  color: #d4d4d4;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 13px;
  line-height: 1.6;
  cursor: pointer;
  transition: all 0.2s ease;
}

.code-line:hover {
  background: #2d2d2d;
}

.code-line.marked {
  background: rgba(230, 162, 60, 0.2);
}

.code-line.correct {
  background: rgba(103, 194, 58, 0.2);
}

.code-line.wrong {
  background: rgba(245, 108, 108, 0.2);
}

/* Bug类型选择 */
.bug-types {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.bug-type-btn {
  height: 50px;
}
</style>

